<?php
/**
 * User zgh
 * Email 1803897171@qq.com
 * Date 2021/7/13
 **/

namespace app\admin\middleware;


use app\admin\service\LoginService;
use app\common\Annotation\ControllerAnnotation;
use app\common\Annotation\NodeAnotation;
use app\common\service\AuthService;
use Doctrine\Common\Annotations\AnnotationReader;
use think\facade\Request;

class AuthMiddleware
{

    const TYPE_NO_LOGIN = 0;
    const TYPE_LOGON = 1;
    const TYPE_AUTH = 2;

    protected static $NO_LOGIN_REDIRECT = "login/index";
    protected static $NO_RIGHT_REDIRECT = "login/no_right";

    /**
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Redirect
     */
    public function handle($request, \Closure $next)
    {
        $current_node = AuthService::getCurrentNode();
        $current_controller_class = AuthService::getCurrentControllerClass();
        $auth_type = self::TYPE_LOGON;
        try {
            $reflectionClass = new \ReflectionClass($current_controller_class);
            $reflectionMethod = $reflectionClass->getMethod(Request::action());
        } catch (\Exception $exception) {
            $error_content = get_404_content();
            return response($error_content, 404);
        }
        try {
            $reader = new AnnotationReader();
            $class_annotation = $reader->getClassAnnotation($reflectionClass, ControllerAnnotation::class);
            $method_annotation = $reader->getMethodAnnotation($reflectionMethod, NodeAnotation::class);
            if ($class_annotation !== null && isset($class_annotation->auth)) {
                $auth_type = $class_annotation->auth;
            }
            if ($method_annotation !== null && isset($method_annotation->auth)) {
                $auth_type = $method_annotation->auth;
            }
        } catch (\Exception $exception) {
        }
        if ($auth_type == self::TYPE_NO_LOGIN) {
            return $next($request);
        } else {
            $admin_id = LoginService::getAdminId();
            $is_user_login = LoginService::isLogin();
            $is_super_manager = LoginService::isSuperManger($admin_id);
            if (!$is_user_login) {
                return redirect(self::$NO_LOGIN_REDIRECT);
            }
            if ($auth_type == self::TYPE_LOGON || $is_super_manager) {
                return $next($request);
            }
            $admin_node_arr = LoginService::getAdminNodeArr($admin_id);
            if (in_array($current_node, $admin_node_arr)) {
                return $next($request);
            } else {
                if (Request::isAjax()) {
                    return json_response("没有操作权限");
                } else {
                    return redirect(self::$NO_RIGHT_REDIRECT);
                }
            }
        }
    }
}